package com.tangdi.production.mpaychl.service.impl.getway;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.tangdi.production.mpaychl.base.service.BaseTranService;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.TranException;
import com.tangdi.production.mpbase.util.HttpUtil;
import com.tangdi.production.mpbase.util.MapUtils;
import com.tangdi.production.mpbase.util.ObjectUtil;
import com.tangdi.production.tdbase.util.MD5Util;

@Service("GETWAY_SERVICE")
public class GetWayServiceImpl implements BaseTranService {
	private static final Logger logger = LoggerFactory.getLogger(GetWayServiceImpl.class);
	
//	private static final String pay_notify_url = "http://ce.imbitpay.com:6983/mpcctp/getway/notify-url.json";
	private static final String pay_notify_url = "http://ce.imbitpay.com:8083/mpcctp/getway/notify-url.json";
	
    private static final String PAY_REQ_URL = "https://www.caisxbb.top/api/v2/boot/pay";
    
    private static final String merchant_Id = "436499";
    public static final String SIGNKEY = "03BB7C27F76F6C5B9246DA902FCBB0E1";
    
	@Override
	public Map<String, Object> execute(Map<String, Object> params) throws TranException {
		try {
			String pay_orderid = "" + params.get("prdordno");
			String pay_callbackurl = "" + params.get("frontUrl"); //回调地址
			String payAmt = ObjectUtil.getString(params.get("payAmt"));
			logger.info("支付金额[{}分]", payAmt);
/*			payAmt = MoneyUtils.toStrYuan(payAmt);
			logger.info("支付金额转换为元[{}]", payAmt);*/

			Map<String, Object> reqParams = new HashMap<>();
			reqParams.put("merchantId", merchant_Id);
			reqParams.put("orderAmt", payAmt);
			reqParams.put("merOrderId", pay_orderid);
			reqParams.put("body", "网银支付");
			reqParams.put("reqNo", RandomStringUtils.randomAlphabetic(20));
			reqParams.put("payType", "13");
			reqParams.put("subType", "13");
			reqParams.put("notifyUrl", pay_notify_url);
			reqParams.put("frontUrl", pay_callbackurl);
			
			reqParams.put("sign", sign(reqParams, SIGNKEY));
			
			Map<String, Object> requestHead = new LinkedHashMap<>();
			String resStr = HttpUtil.httpRequest(PAY_REQ_URL, reqParams, "POST", "UTF-8", requestHead);
			logger.info("返回参数:{}", resStr);
			
			if ("00".equals(JSON.parseObject(resStr).getString("code"))){
				
				StringBuilder returtnHtml = new StringBuilder();
				returtnHtml.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" /></head><body><script language=\"javascript\">window.onload=function(){document.payfrm.submit();}</script>");
				returtnHtml.append("<form id=\"payfrm\" name=\"payfrm\" action=\"").append(JSON.parseObject(JSON.parseObject(resStr).getString("data")).get("payInfo")).append("\" method=\"get\" >");
				returtnHtml.append("</form></body></html>");
				
				Map<String,Object> backMap = new HashMap<>();
				backMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
				backMap.put("contentType", MsgCT.DATA_TYPE_HTML);
				backMap.put("busContent", returtnHtml.toString());
				return backMap;
			} else {
				Map<String,Object> backMap = new HashMap<>();
				backMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
				backMap.put("contentType", MsgCT.DATA_TYPE_STRING);
				backMap.put("busContent", JSON.parseObject(resStr).getString("resMessage"));
				return backMap;
			}
		} catch (Exception e){
			logger.error("处理Ksunpay支付通道异常:{}", e.getMessage(), e);
			Map<String,Object> backMap = new HashMap<>();
			backMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
			backMap.put("msg", "支付渠道调用异常:" + e.getMessage());
			return backMap;
		}
	}
	
	public static void main(String[] args) throws Exception {
		
		String url = "https://www.caisxbb.top/api/v2/boot/pay";
		String SIGNKEY = "33F8945257FC3A56E55D56B002A37D89";
		
		Map<String, Object> params = new HashMap<>();
		params.put("merchantId", "16782297");
		params.put("orderAmt", "101");
		params.put("merOrderId", System.currentTimeMillis() + RandomStringUtils.randomAlphabetic(5));
		params.put("body", "网银支付");
		params.put("reqNo", RandomStringUtils.randomAlphabetic(20));
		params.put("payType", "13");
		params.put("subType", "13");
		params.put("notifyUrl", "http://58.220.30.99:8081/qrcode-starter/returnTest");
		params.put("frontUrl", "http://58.220.30.99:8081/qrcode-starter/returnTest");
		
		params.put("sign", sign(params, SIGNKEY));
		System.out.println("url:" + url);
		System.out.println("map:"+ params.toString());
		
		Map<String, Object> requestHead = new LinkedHashMap<>();
		String resStr = HttpUtil.httpRequest(url, params, "POST", "UTF-8", requestHead);
		System.out.println(resStr);
		System.out.println(JSON.parseObject(JSON.parseObject(resStr).getString("data")).get("payInfo"));
	}
	
	private static String sign(Map<String, Object> paramMap, String signKey) {
		String signStr = MapUtils.getSignStrByTreeMap(paramMap, true);
		signStr += "&key=" + signKey;
		// String signValue = MD5.encryption(signStr).toUpperCase();
		
		System.out.println("signStr:");
		String signValue = MD5Util.digest(signStr).toLowerCase();
		return signValue;
	}
}
